# -*- coding: utf-8 -*-

"""

    use adb to capture the phone screen
    then use hanwang text recognize the text
    then use baidu to search answer

"""
import platform
from datetime import datetime
import os
import sys
from shutil import copyfile

from PIL import Image

def get_adb_tool():
    system_version = platform.system().upper()
    adb_bin = ""
    parent = "adb"
    if system_version.startswith("LINUX"):
        adb_bin = os.path.join(parent, "linux", "adb")
    if system_version.startswith("WINDOWS"):
        adb_bin = os.path.join(parent, "win", "adb.exe")
    if system_version.startswith("DARWIN"):
        adb_bin = os.path.join(parent, "mac", "adb")
    return adb_bin


def check_screenshot(filename, directory):
    """
    检查获取截图的方式
    """
    save_shot_filename = os.path.join(directory, filename)
    global SCREENSHOT_WAY
    if os.path.isfile(save_shot_filename):
        try:
            os.remove(save_shot_filename)
        except Exception:
            pass
    if SCREENSHOT_WAY < 0:
        print("暂不支持当前设备")
        sys.exit()
    capture_screen(filename, directory)
    try:
        Image.open(save_shot_filename).load()
        print("采用方式 {} 获取截图".format(SCREENSHOT_WAY))
    except Exception:
        SCREENSHOT_WAY -= 1
        check_screenshot(filename=filename, directory=directory)


def capture_screen(directory="."):
    """
    capture screen to screenshot.png
    """
    screenshot_filename = "screenshot.png"
    save_text_area = os.path.join(directory, screenshot_filename)
    capture_screen(screenshot_filename, directory)


def analyze_picture_text(crop_area, image, dst_file_name, compress_level=1):
    """
    analyze crop_area screen picture data
    """
    parse_answer_area(image, dst_file_name, compress_level, crop_area)
    return get_area_data(dst_file_name)


def analyze_stored_screen_text(screenshot_filename="screenshot.png", directory=".", compress_level=1):
    """
    reload screen from stored picture to store
    :param directory:
    :param compress_level:
    :return:
    """
    save_text_area = os.path.join(directory, "text_area.png")
    parse_answer_area(os.path.join(directory, screenshot_filename), save_text_area, compress_level)
    return get_area_data(save_text_area)

def capture_screen(filename="screenshot.png", directory="."):
    """
    use adb tools

    :param filename:
    :param directory:
    :return:
    """
    os.system("adb shell screencap -p /sdcard/{0}".format(filename))
    os.system("adb pull /sdcard/{0} {1}".format(filename, os.path.join(directory, filename)))


def save_screen(filename="screenshot.png", directory="."):
    """
    Save screen for further test
    :param filename:
    :param directory:
    :return:
    """
    copyfile(os.path.join(directory, filename),
             os.path.join(directory, datetime.now().strftime("%m%d_%H%M%S").join(os.path.splitext(filename))))


def parse_answer_area(image, dst_file_name, compress_level, crop_area):
    """
    crop the answer area

    :return:
    """
    if compress_level == 1:
        image = image.convert("L")
    elif compress_level == 2:
        image = image.convert("1")

    width, height = image.size[0], image.size[1]
    #print("screen width: {0}, screen height: {1}".format(width, height))

    region = image.crop((width * crop_area[0], height * crop_area[1], width * crop_area[2], height * crop_area[3]))

    region.save(dst_file_name)

    """
    import numpy as np
    from skimage import morphology
    image = image.convert("L")
    array_img = np.array(image)
    ot_img = (array_img > 225)
    obj_dtec_img = morphology.remove_small_objects(ot_img, min_size=width * height / 4, connectivity=1)
    if np.sum(obj_dtec_img) < 1000:
        return False
    region = image.crop((
        np.where(obj_dtec_img * 1.0 > 0)[ 1 ].min() + 20,
        np.where(obj_dtec_img * 1.0 > 0)[ 0 ].min() + 215,
        np.where(obj_dtec_img * 1.0 > 0)[ 1 ].max(),
        np.where(obj_dtec_img * 1.0 > 0)[ 0 ].max()))

    region.save(dst_file_name + ".png")
    
"""

def get_area_data(text_area_file):
    """

    :param text_area_file:
    :return:
    """
    with open(text_area_file, "rb") as fp:
        image_data = fp.read()
        return image_data
    return ""
